package com.atos.optical.service.impl;

import cn.hutool.core.util.StrUtil;
import com.atos.optical.common.BaseServiceImpl;
import com.atos.optical.common.ServiceException;
import com.atos.optical.mapper.SysShopInfoMapper;
import com.atos.optical.model.po.SysShopInfo;
import com.atos.optical.model.query.SysShopInfoQuery;
import com.atos.optical.service.SysShopInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wanghra
 * @version 1.0
 * @description
 * @date 2025/8/13
 */
@Slf4j
@Service
public class SysShopInfoServiceImpl extends BaseServiceImpl<SysShopInfoMapper,
        SysShopInfo> implements SysShopInfoService {
    @Autowired
    private SysShopInfoMapper mapper;

    @Override
    @Transactional
    public boolean save(SysShopInfo entity) {
        check(entity);
        return super.save(entity);
    }

    @Override
    @Transactional
    public boolean updateById(SysShopInfo entity) {
        check(entity);
        return super.updateById(entity);
    }

    @Override
    public SysShopInfoQuery pageByQuery(SysShopInfoQuery query) {
        query.setOrders(OrderItem.descs("CREATE_TIME", "MODIFY_TIME"));
        mapper.pageByQuery(query);
        return query;
    }
    
    private void check(SysShopInfo entity) {
        if (isExistShopName(entity)) {
            throw new ServiceException("门店名称重复！");
        }
    }
    
    private boolean isExistShopName(SysShopInfo entity) {
        QueryWrapper<SysShopInfo> query = new QueryWrapper<>();
        query.lambda().ne(StrUtil.isNotBlank(entity.getShopId()), SysShopInfo::getShopId, entity.getShopId())
                .eq(SysShopInfo::getShopName, entity.getShopName());
        return 0 < mapper.selectCount(query);
    }
}
